﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using ELearning.BLL;
using ELearning.Common;
using ELearning.Common.CommonStr;
using ELearning.Common.Extensions;
using ELearning.Common.Helpers;
using ELearning.Common.Http;
using ELearning.Common.Model;
using ELearning.Models;
using ELearning.Models.ViewModel.Message;
using RestSharp;

namespace ConsoleJobs.Jobs
{
    public class SendMsgJob
    {
        /// <summary>
        /// 消息操作service
        /// </summary>
        private static EMessageService MessageService => new EMessageService();

        /// <summary>
        /// 消息记录操作service
        /// </summary>
        private static EMessageLogService MessageLogService => new EMessageLogService();

        /// <summary>
        /// 用户操作service
        /// </summary>
        private static ESysUserService ESysUserService => new ESysUserService();

        /// <summary>
        /// 发送消息
        /// 每次只去一条需要发送的消息
        /// 原因：如果取出所有待发送的列表的话，有可能发送一条消息需要1个小时，假设作业的间隔是1分钟，那么有可能造成同一条消息发送50多次给同一个人
        /// </summary>
        public static ServiceResponse<int> PublishModel()
        {
            try
            {
                //var id = Guid.Parse("A3421806-7544-46E3-9A95-016DBCFB96FC");
                //var message = MessageService.Find(m => !m.IsDelete && m.Id == id);
                var message = MessageService.Find(m => !m.IsDelete && m.State == 3);
                if (message == null)
                    return ServiceResponse<int>.SuccessResponse(CommonConst.OprateSuccessStr, 1);
                var users = ESysUserService.GetSendUserByMsgId(message.Id);
                var name = message.Creater;
                message.State = 4; //发送中
                message.ModifyTime = DateTime.Now;
                MessageService.Update(message);
                foreach (var user in users)
                {
                    if (user.UserType != UserType.UserTypeJK && user.UserType != UserType.UserTypeXSZS)
                    {
                        continue;
                    }

                    if (user.UserType == UserType.UserTypeJK)
                    {
                        if (string.IsNullOrEmpty(user.AgentNumber) || string.IsNullOrEmpty(user.Unumber))
                        {
                            var log1 = new EMessageLog
                            {
                                CreateTime = DateTime.Now,
                                Creater = name,
                                Id = GuidUtil.NewSequentialId(),
                                IsDelete = false,
                                MessageId = message.Id,
                                Note = $"{user.UserName}该用户没有经销商编号或者职员编码",
                                Status = false,
                                UserId = user.UserID
                            };
                            if (MessageLogService.Find(l => !l.IsDelete && l.MessageId == log1.MessageId && l.UserId == log1.UserId) == null)
                                MessageLogService.Add(log1);
                            continue;
                        }

                        var res = SendMsg(user.AgentNumber, message.Text, user.Unumber);
                        var log = new EMessageLog
                        {
                            CreateTime = DateTime.Now,
                            Creater = name,
                            Id = GuidUtil.NewSequentialId(),
                            IsDelete = false,
                            MessageId = message.Id,
                            Note = $"res:{res.ToJson()},params:AgentNumber;{user.AgentNumber},Text;{message.Text},AgentNumber;{user.Unumber}",
                            Status = res.status,
                            UserId = user.UserID
                        };
                        if (MessageLogService.Find(l => !l.IsDelete && l.MessageId == log.MessageId && l.UserId == log.UserId) == null)
                            MessageLogService.Add(log);
                    }

                    if (user.UserType == UserType.UserTypeXSZS)
                    {
                        if (string.IsNullOrEmpty(user.AgentNumber))
                        {
                            var log1 = new EMessageLog
                            {
                                CreateTime = DateTime.Now,
                                Creater = name,
                                Id = GuidUtil.NewSequentialId(),
                                IsDelete = false,
                                MessageId = message.Id,
                                Note = $"{user.UserName}该用户没有经销商编号",
                                Status = false,
                                UserId = user.UserID
                            };
                            if (MessageLogService.Find(l => !l.IsDelete && l.MessageId == log1.MessageId && l.UserId == log1.UserId) == null)
                                MessageLogService.Add(log1);
                            continue;
                        }
                        var res = SendXszsMsg(user.AgentNumber, message.Text, user.Unumber, user.UserName, message.Title, message.Id.ToString());
                        var log = new EMessageLog
                        {
                            CreateTime = DateTime.Now,
                            Creater = name,
                            Id = GuidUtil.NewSequentialId(),
                            IsDelete = false,
                            MessageId = message.Id,
                            Note = res.ToJson(),
                            Status = res.success,
                            UserId = user.UserID
                        };
                        if (MessageLogService.Find(l => !l.IsDelete && l.MessageId == log.MessageId && l.UserId == log.UserId) == null)
                            MessageLogService.Add(log);
                    }

                }
                message.SendTime = DateTime.Now;
                message.State = 2;
                message.ModifyTime = DateTime.Now;
                MessageService.Update(message);
                return ServiceResponse<int>.SuccessResponse(CommonConst.OprateSuccessStr, 1);
            }
            catch (Exception ex)
            {
                return ServiceResponse<int>.WarningResponse(ex.Message);
            }
        }

        /// <summary>
        /// 发送消息
        ///	status：true/false（成功/失败）
        ///	msg：提示消息
        ///	errorMsg: 异常提醒（http status 不为200时返回）
        ///	data: 返回数据结构体
        ///	http status：200代表请求成功
        ///                ：401/400 异常
        /// </summary>
        /// <param name="dealerCode">经销商代码:(AgentNumber)</param>
        /// <param name="msgContent">消息体</param>
        /// <param name="employeeNo">员工编号(Unumber)</param>
        private static MessageSendRespViewModel SendMsg(string dealerCode, string msgContent, string employeeNo)
        {
            try
            {
                var res = HttpClientHelper.HttpPost(AppConfig.SendMsgRequest, "{\r\n\"dealerCode\":\"" + dealerCode + "\",\r\n\"msgContent\":\"" + msgContent + "\",\r\n\"employeeNo\":\"" + employeeNo + "\"\r\n}\r\n");
                var m = res.ToObject<MessageSendRespViewModel>();

                return m;
            }
            catch (Exception ex)
            {
                return new MessageSendRespViewModel
                {
                    status = false,
                    msg = "失败",
                    errorMsg = ex.Message
                };
            }
        }

        /// <summary>
        /// 销售助手发送消息
        /// </summary>
        /// <param name="jxsh">经销商号码</param>
        /// <param name="content">消息内容</param>
        /// <param name="czydm">操作员代码</param>
        /// <param name="czymc">操作员名称</param>
        /// <param name="title">消息标题</param>
        /// <param name="messageId">消息id</param>
        /// <returns></returns>
        private static XszsMessageSendRespViewModel SendXszsMsg(string jxsh, string content, string czydm, string czymc, string title, string messageId)
        {
            try
            {
                var appId = MessageConfig.AppId;
                var appKey = MessageConfig.AppKey;
                var timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
                var nonce = "xszs";
                var sign = (appId + appKey + timestamp + nonce).ToMD5_32();
                var source = "TrainingSystem";

                var jsonModel = new MessageSendModel
                {
                    jxsh = jxsh,
                    content = content,
                    czydm = czydm,
                    id = messageId,
                    czymc = czymc,
                    source = source,
                    title = title
                };
                var json = jsonModel.ToJson();

                var client = new RestClient(MessageConfig.PushUrl);
                var request = new RestRequest(Method.POST);
                request.AddHeader("cache-control", "no-cache");
                request.AddHeader("sign", sign);
                request.AddHeader("nonce", nonce);
                request.AddHeader("timestamp", timestamp);
                request.AddHeader("appId", appId);
                request.AddParameter("undefined", json, ParameterType.RequestBody);
                var response = client.Execute(request);
                var iss = response.IsSuccessful;
                var resContent = response.Content;
                //Console.WriteLine($"iss:{iss},json:{json}");
                //Console.WriteLine(resContent);
                //Console.WriteLine("------------------------------------------------------------------------------");
                if (!iss)
                    return new XszsMessageSendRespViewModel
                    {
                        success = false,
                        data = resContent,
                        error = $"接口请求失败,参数：{json}"
                    };

                var m = resContent.ToObject<XszsMessageSendRespViewModel>();

                return m;
            }
            catch (Exception ex)
            {
                return new XszsMessageSendRespViewModel
                {
                    success = false,
                    data = "失败",
                    error = ex.Message
                };
            }
        }
    }

}
